﻿// Mike Woodring
// http://www.bearcanyon.com
//
using System;
using System.Reflection;
using System.Collections;
using System.Xml;
using System.Configuration;
using System.Runtime.CompilerServices;



public class AssemblySettings
{
    private IDictionary settings;

    [MethodImpl(MethodImplOptions.NoInlining)]
    public AssemblySettings()
        : this(Assembly.GetCallingAssembly())
    {
    }

    public AssemblySettings(Assembly asm)
    {
        settings = GetConfig(asm);
    }

    public string this[string key]
    {
        get
        {
            string settingValue = null;

            if (settings != null)
            {
                settingValue = settings[key] as string;
            }

            return (settingValue == null ? "" : settingValue);
        }
    }

    public static IDictionary GetConfig()
    {
        return GetConfig(Assembly.GetCallingAssembly());
    }

    public static IDictionary GetConfig(Assembly asm)
    {
        // Open and parse configuration file for specified
        // assembly, returning collection to caller for future
        // use outside of this class.
        //
        try
        {
            string cfgFile = asm.CodeBase + ".config";
            const string nodeName = "assemblySettings";

            XmlDocument doc = new XmlDocument();
            doc.Load(new XmlTextReader(cfgFile));

            XmlNodeList nodes = doc.GetElementsByTagName(nodeName);

            foreach (XmlNode node in nodes)
            {
                if (node.LocalName == nodeName)
                {
                    DictionarySectionHandler handler = new DictionarySectionHandler();
                    return (IDictionary)handler.Create(null, null, node);
                }
            }
        }
        catch
        {
        }

        return (null);
    }
}
